import { message, Upload } from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import type { GetProp, UploadProps } from 'antd'
import { useState } from 'react'
import { imgUrl } from '@/util/constant'
import type { UploadFile } from 'antd/es/upload/interface'

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0]

interface Props {
  // 图片列表
  fileList: UploadFile[]
  // 触发上传
  onChange: (fileList: UploadFile[]) => void
  // 判断是头像还是题目，后端好分文件夹摆放
  sort: string
}

// 上传之前的操作（图片的格式，图片的上传大小)
const beforeUpload = (file: FileType) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('你只能上传 JPG/PNG 图片!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小必须小于 2MB!')
  }
  return isJpgOrPng && isLt2M
}

// 图片上传组件
export default function YuUpload(props: Props) {
  const { fileList, onChange, sort } = props

  // 加载
  const [loading, setLoading] = useState(false)

  // 上传按钮
  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>上传</div>
    </button>
  )

  // 触发上传
  const hanldChange: UploadProps['onChange'] = info => {
    console.log(info)
    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      setLoading(false)
      // 子传父
      onChange([
        {
          uid: info.file.response.data,
          name: info.file.response.data,
          status: 'done',
          url: imgUrl + info.file.response.data
        }
      ])
    }
  }

  // action 属性起着关键作用，它主要用于指定文件上传的服务器地址
  return (
    <Upload name="file" listType="picture-circle" data={{ sort }} className="avatar-uploader" showUploadList={false} action="http://localhost:3333/upload/image" withCredentials={true} beforeUpload={beforeUpload} onChange={hanldChange}>
      {fileList[0]?.url ? <img src={fileList[0]?.url} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
    </Upload>
  )
}
